package cn.bearspark.merit.provider.dao.buffer;

import cn.bearspark.framework.redis.starter.buffer.zset.RedisZSetBuffer;
import cn.bearspark.merit.provider.dao.key.AccMeritUserIdBufferKeyBuilder;
import cn.bearspark.merit.provider.dao.mapper.AccMeritMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 积功德的用户 id 的 ZSet 数据结构的缓存器
 *
 * @author f
 */
@Component
public class AccMeritUserIdZSetBuffer extends RedisZSetBuffer {

    private final AccMeritMapper accMeritMapper;

    private final AccMeritUserIdBufferKeyBuilder keyBuilder;

    public AccMeritUserIdZSetBuffer(RedisTemplate<String, Object> redisTemplate,
                                    AccMeritMapper accMeritMapper,
                                    AccMeritUserIdBufferKeyBuilder keyBuilder) {
        super(redisTemplate);
        this.accMeritMapper = accMeritMapper;
        this.keyBuilder = keyBuilder;
    }

    /**
     * 判断指定用户是否向指定模块下的指定数据积过功德
     *
     * @param userId       指定的用户 id
     * @param moduleCode   指定的模块的枚举值
     * @param moduleDataId 指定数据的主键 id
     * @return 指定用户是否向指定模块下的指定数据积过功德
     */
    public boolean exists(long userId, int moduleCode, long moduleDataId) {
        return super.exists(
                keyBuilder.buildAccMeritUserIdZSetKey(moduleCode, userId),
                moduleDataId,
                () -> accMeritMapper.countAccMerit(userId, moduleCode, moduleDataId)
        );
    }
}
